import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get_it/get_it.dart';

import 'package:home_framework/api/dynamic_service.dart';
import 'package:home_framework/interfaces/dynamic_listener.dart';
import 'package:home_framework/models/dynamic_entity.dart';
import 'package:home_framework/utils/dialogs.dart';
import 'api/upload_service.dart';
import 'dynamic_form.dart';

class DynamicEdit extends StatefulWidget {
  final String dynamicId;
  DynamicEdit(this.dynamicId, {Key key}) : super(key: key);

  @override
  _DynamicEditState createState() => _DynamicEditState();
}

class _DynamicEditState extends State<DynamicEdit> {
  Map<String, Map<String, Object>> _formData;
  DynamicEntity _dynamicEntity;
  File _imageFile;
  String _imageUrl;

  void _getDynamic(String id) async {
    var response = await DynamicService.get(id);
    if (response != null && response.statusCode == 200) {
      _dynamicEntity = DynamicEntity.fromJson(response.data);
      setState(() {
        _formData = {
          'title': {
            'value': _dynamicEntity.title,
            'controller': TextEditingController(text: _dynamicEntity.title),
            'icon': Icons.title,
            'obsecure': false,
          },
          'content': {
            'value': _dynamicEntity.content,
            'controller': TextEditingController(text: _dynamicEntity.content),
            'icon': Icons.content_paste,
            'obsecure': false,
          },
        };
        _imageUrl = _dynamicEntity.imageUrl;
      });
    } else {
      Dialogs.showInfo(this.context, '加载数据失败');
      Navigator.of(context).pop();
    }
  }

  @override
  void initState() {
    super.initState();

    _getDynamic(widget.dynamicId);
  }

  _handleTextFieldChanged(String formKey, String value) {
    this.setState(() {
      _formData[formKey]['value'] = value;
    });
  }

  _handleClear(String formKey) {
    this.setState(() {
      _formData[formKey]['value'] = '';
      (_formData[formKey]['controller'] as TextEditingController)?.clear();
    });
  }

  _handleImagePicked(File imageFile) {
    setState(() {
      _imageFile = imageFile;
    });
  }

  _handleSubmit() async {
    if ((_formData['title']['value'] as String).trim() == '') {
      Dialogs.showInfo(this.context, '标题不能为空');
      return;
    }

    if ((_formData['content']['value'] as String).trim() == '') {
      Dialogs.showInfo(this.context, '内容不能为空');
      return;
    }

    EasyLoading.showInfo('请稍候...', maskType: EasyLoadingMaskType.black);

    Map<String, String> newFormData = {};
    _formData.forEach((key, value) {
      newFormData[key] = value['value'];
    });
    if (_imageFile != null) {
      var imageResponse = await UploadService.uploadImage('image', _imageFile);
      if (imageResponse.statusCode == 200) {
        newFormData['imageUrl'] = imageResponse.data['id'];
      } else {
        Dialogs.showInfo(this.context, '图片上传失败');
        return;
      }
    }
    var response = await DynamicService.update(_dynamicEntity.id, newFormData);
    if (response.statusCode == 200) {
      Dialogs.showInfo(context, '保存成功');
      //处理成功更新后的业务
      _handleUpdated(newFormData);
      Navigator.of(context).pop();
    } else {
      Dialogs.showInfo(this.context, response.statusMessage);
    }
    EasyLoading.dismiss();
  }

  void _handleUpdated(Map<String, String> newFormData) {
    _dynamicEntity.title = newFormData['title'];
    _dynamicEntity.content = newFormData['content'];
    if (newFormData.containsKey('imageUrl')) {
      _dynamicEntity.imageUrl = newFormData['imageUrl'];
    }
    GetIt.instance.get<DynamicListener>().dynamicUpdated(
          _dynamicEntity.id,
          _dynamicEntity,
        );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('编辑动态'),
        brightness: Brightness.dark,
      ),
      body: _getFormWidgets(),
    );
  }

  _getFormWidgets() {
    if (_formData == null)
      return Center(
        child: Text('加载中...'),
      );
    return DynamicForm(
      _formData,
      _handleTextFieldChanged,
      _handleClear,
      '保存',
      _handleSubmit,
      _handleImagePicked,
      imageFile: _imageFile,
      imageUrl: _imageUrl,
    );
  }
}
